"""
日志配置模块
"""
import os
import sys
from loguru import logger
from config.settings import settings


def setup_logger():
    """配置日志系统"""
    
    # 移除默认的日志处理器
    logger.remove()
    
    # 确保日志目录存在
    log_dir = os.path.dirname(settings.log_file)
    if log_dir and not os.path.exists(log_dir):
        os.makedirs(log_dir)
    
    # 控制台输出
    logger.add(
        sys.stdout,
        level=settings.log_level,
        format="<green>{time:YYYY-MM-DD HH:mm:ss}</green> | "
               "<level>{level: <8}</level> | "
               "<cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> | "
               "<level>{message}</level>",
        colorize=True
    )
    
    # 文件输出
    logger.add(
        settings.log_file,
        level=settings.log_level,
        format="{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {name}:{function}:{line} | {message}",
        rotation="100 MB",  # 文件大小轮转
        retention="30 days",  # 保留30天
        compression="zip",  # 压缩旧日志
        encoding="utf-8"
    )
    
    # 错误日志单独记录
    logger.add(
        settings.log_file.replace('.log', '_error.log'),
        level="ERROR",
        format="{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {name}:{function}:{line} | {message}",
        rotation="50 MB",
        retention="60 days",
        compression="zip",
        encoding="utf-8"
    )
    
    return logger


# 初始化日志
audit_logger = setup_logger()
